package com.yanliang.server;

import com.yanliang.model.*;
import com.yanliang.servlet.HttpServlet;
import com.yanliang.servlet.Servlet;
import com.yanliang.utils.StaticResourceUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.List;

/**
 * @author yanliang
 * @date 5/10/20203:34 PM
 */
public class RequestProcessor extends Thread {

	private Socket socket;
	private List<MyHost> hostList;

	public RequestProcessor(Socket socket, List<MyHost> hostList) {
		this.socket = socket;
		this.hostList = hostList;
	}

	@Override
	public void run() {
		try {
			InputStream inputStream = socket.getInputStream();
			Request request = new Request(inputStream);
			Response response = new Response(socket.getOutputStream());

			//请求URL
			String url = request.getUrl();
			String[] urlArr = url.split("/");

			//根据URL匹配资源
			Servlet servlet = null;
			MyContext context = StaticResourceUtil.getContext(url, hostList);
			if (context != null) {
				List<MyWrapper> wrapperList = context.getWrapperList();
				if (wrapperList != null && !wrapperList.isEmpty()) {
					for (MyWrapper wrapper : wrapperList) {
						if (wrapper.getUrlPattern().equals(url)) {
							servlet = wrapper.getServlet();
							break;
						}
					}
				}
			}

			//静态资源处理
			if (servlet == null) {
				response.outputHtml();
			} else {
				//动态资源servlet请求
				//执行servlet
				HttpServlet httpServlet = (HttpServlet) servlet;
				httpServlet.service(request, response);
			}

			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
